package com.servlet;


import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/download.do")
public class DownloadFileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //getWriter() has already been called for this response
//        PrintWriter writer = resp.getWriter();
        ServletOutputStream outputStream = resp.getOutputStream();
        //用File文件类 指向作为下载的文件
        File file = new File("D:\\imgUpload\\1.jpg");
        //通过设置响应头信息，告诉浏览器 接下来的数据 是一个需要被下载的文件
        resp.setHeader("content-disposition", "attachment;filename=" + "中文图片.jpg");
        //获取文件的输入流 对源文件进行读取
        FileInputStream fis = new FileInputStream(file);
        //定义一个缓冲字节数组 用于字节数据的搬运
        byte[] buffer = new byte[1024];
        int length = 0;
        while ((length = fis.read(buffer)) != -1) {
            outputStream.write(buffer);
            outputStream.flush();
        }
        fis.close();
        outputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
